// manager/pages/addbuilding/index.js
import config from '../../../utils/config';
import { request, uploadFile } from '../../../utils/request';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: { 
        baseUrl: config.baseUrl,
        disabled: false,
        latitude: "",
        longitude: "",  
        form: {
            id: "",
            locationName: "",
            locationAbbreviation: "",
            locationPic: "",
            locationCoordinate: "",
            locationAddress: "",
            locationLayers: "",
            locationContacts: "",
            locationPhone: "",
            locationType: 1,
            remark: "",
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.id){
            this.setData({
                'form.id': options.id
            })
            wx.setNavigationBarTitle({
                title: "编辑楼宇"
            })
            this.getLocationInfo();
        }else{
            // 获取当前位置
            this.getLatLng();
        }
        if(options.type == "view"){
            wx.setNavigationBarTitle({
                title: "楼宇详情"
            })
            this.setData({
                disabled: true
            })
        }
        this.initValidate();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })     
    },

    // 调整定位
    fineLocation(e){
        let that = this;
        wx.chooseLocation({
            latitude: this.data.latitude,
            longitude: this.data.longitude,
            scale: 18,
            success(res){
                console.log(res)
                let latitude = res.latitude;
                let longitude = res.longitude;
                that.getCoordinatePositionInfo(latitude,longitude)
            }
        })
    },
    
    // 获取经纬度
    getLatLng(){
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.log(res)
                if (res.authSetting['scope.userLocation'] == false) {//非初始化进入该页面,且未授权
                    wx.showModal({
                        title: '是否授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: function (data) {
                                        // console.log(data);
                                        if (data.authSetting["scope.userLocation"] == true) {
                                            that.getLocation();
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else {//初始化进入
                    // console.log("KKKKK") 
                    that.getLocation();
                }
            }
        })
    },
    getLocation(){
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success (res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                })
                that.getCoordinatePositionInfo(res.latitude,res.longitude)
            },
            complete: function(res) {
                console.log(res)
                if(res.errMsg == "getLocation:fail auth deny"){
                    // wx.showToast({
                    //     title: '获取定位失败',
                    //     icon: 'none',
                    //     duration: 2000
                    // });
                }
            }
        })
    },
    getCoordinatePositionInfo(latitude,longitude){
        let { form } = this.data;
        request({
            url: "/commonApi/getCoordinatePositionInfo",
            method: "GET",
            data: {
                coordinate: `${latitude},${longitude}`
            }
        }).then(res => {
            if(res.code == 0){
                form.locationCoordinate = `${latitude},${longitude}`;
                form.locationAddress = res.data.address;
                this.setData({
                    form,
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 楼宇图片上传
    uploadImage(e) { // 拍摄或从相册选取上传
        let { key, url } = e.detail;
        uploadFile({
            url: "/commonApi/imageUploadAddWatermark",
            filePath: url,
            name: "imgfile",
            formData: {
                coordinate: this.data.form.locationCoordinate,
                watermark: this.data.form.locationAddress,
                fileName: key
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    ['form.'+key]: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
                
    },
    // 保存楼宇
    save(e) {
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        request({
            url: `/enterpriseMarketing/addLocationInfo`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                setTimeout(()=>{
                    wx.navigateBack()
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 楼宇信息
    getLocationInfo(){
        request({
            url: "/enterpriseMarketing/getLocationInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.id
            }
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                for(let key in form){
                    form[key] = res.data[key];
                }
                let latitude = res.data.locationCoordinate.split(",")[0];
                let longitude = res.data.locationCoordinate.split(",")[1]; 
                this.setData({
                    form,
                    latitude,
                    longitude
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            locationName: {
                required: true
            },
            locationAbbreviation: {
                required: true
            },
            locationPic: {
                required: true
            },
            locationCoordinate: {
                required: true
            },
            locationLayers: {
                required: true,
                digits: true,
                min: 1
            }
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            locationName: {
                required: '请输入楼宇名称'
            },
            locationAbbreviation: {
                required: '请输入楼宇简称'
            },
            locationPic: {
                required: '请上传楼宇照片'
            },
            locationCoordinate: {
                required: '请获取楼宇位置'
            },
            locationLayers: {
                required: '请输入总楼层',
                digits: '总楼层为数字',
                min: '总楼层不小于1'
            }
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})